package com.travelplanning.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travelplanning.admin.common.biz.user.UserContext;
import com.travelplanning.admin.common.convention.Result;
import com.travelplanning.admin.common.convention.errorcode.BaseErrorCode;
import com.travelplanning.admin.common.enums.UserErrorCodeEnum;
import com.travelplanning.admin.common.exception.ClientException;
import com.travelplanning.admin.dao.entity.CommentDO;
import com.travelplanning.admin.dao.entity.ContentDO;
import com.travelplanning.admin.dao.entity.UserDO;
import com.travelplanning.admin.dao.mapper.CommentMapeper;
import com.travelplanning.admin.dao.mapper.ContentMapeper;
import com.travelplanning.admin.dto.req.ContentAddReqDTO;
import com.travelplanning.admin.dto.req.ContentQueryReqDTO;
import com.travelplanning.admin.dto.req.queryByContentIdReqDTO;
import com.travelplanning.admin.dto.req.queryByTitleReqDTO;
import com.travelplanning.admin.dto.resp.ContentQueryRespDTO;
import com.travelplanning.admin.service.CommentService;
import com.travelplanning.admin.service.ContentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ContentServiceImpl extends ServiceImpl<ContentMapeper, ContentDO> implements ContentService {


    /**
     * 新增文章
     * @param requestparam
     * @return
     */
//    @Override
//    public void addContent(ContentAddReqDTO requestparam) {
//        ContentDO contentDO = BeanUtil.toBean(requestparam, ContentDO.class);
//        contentDO.setUserId(UserContext.getUserId());
//        contentDO.setUsername(UserContext.getUsername());
//        int insert = baseMapper.insert(contentDO);
//        if (insert<1){
//            throw new ClientException(BaseErrorCode.CONTENT_ADD_ERROR);
//        }
//        return ;
//    }


    /**
     * 新增文章
     * @param requestparam
     */
    @Override
    public void addContent(ContentAddReqDTO requestparam) {
        try {
            ContentDO contentDO = BeanUtil.toBean(requestparam, ContentDO.class);
            // 保证用户信息的正确性和安全性
            String userId = UserContext.getUserId();
            if (userId == null) {
                throw new ClientException(BaseErrorCode.USER_ID_NOT_FOUND);
            }
            String username = UserContext.getUsername();
            if (username == null || username.trim().isEmpty()) {
                throw new ClientException(BaseErrorCode.USERNAME_NOT_FOUND);
            }
            contentDO.setUserId(userId);
            contentDO.setUsername(username);

            // 日志记录数据库操作，有利于问题追踪和性能调优
            log.info("用户上下文获取: {}, username: {}", userId, username);

            int insert = baseMapper.insert(contentDO);
            // 增加更详细的边界条件处理
            if (insert < 1) {
                throw new ClientException(BaseErrorCode.CONTENT_ADD_ERROR);
            }
        } catch (Exception e) {
            // 捕获并处理可能的运行时异常，确保方法的健壮性
            log.error("Exception occurred while adding content", e);
            throw new ClientException(BaseErrorCode.CONTENT_ADD_ERROR);
        }
    }

    public List<ContentQueryRespDTO> queryContent() {
        LambdaQueryWrapper<ContentDO> queryWrapper = Wrappers.lambdaQuery(ContentDO.class)
                .eq(ContentDO::getDelFlag, 0);
         List<ContentDO> contentList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(contentList)) {
            log.info("Content list is empty.");
            return Collections.emptyList(); // 返回空列表，不进行后续操作
        }

        //使用大模型优化
        List<ContentQueryRespDTO> contentQueryRespDTOList = contentList.parallelStream() // 使用并行流提高效率
                .map(contentDO -> {
                    ContentQueryRespDTO contentQueryRespDTO = new ContentQueryRespDTO();
                    // 假设BeanUtil是安全的，且已处理循环引用和深拷贝问题
                    BeanUtil.copyProperties(contentDO, contentQueryRespDTO);
                    return contentQueryRespDTO;
                })
                .collect(Collectors.toList());
        return contentQueryRespDTOList;
    }

    @Override
    public List<ContentQueryRespDTO> queryContentByTitle(queryByTitleReqDTO requestparam) {
        String title = requestparam.getContentTitle();
        LambdaQueryWrapper<ContentDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(title), ContentDO::getTitle, title);

        List<ContentDO> contentList = baseMapper.selectList(wrapper);
        List<ContentQueryRespDTO> contentQueryRespDTOList = contentList.parallelStream() // 使用并行流提高效率
                .map(contentDO -> {
                    ContentQueryRespDTO contentQueryRespDTO = new ContentQueryRespDTO();
                    // 假设BeanUtil是安全的，且已处理循环引用和深拷贝问题
                    BeanUtil.copyProperties(contentDO, contentQueryRespDTO);
                    return contentQueryRespDTO;
                })
                .collect(Collectors.toList());

        return contentQueryRespDTOList;
    }

    @Override
    public ContentQueryRespDTO queryContentById(queryByContentIdReqDTO requestparam) {
        ContentDO contentDO = baseMapper.selectById(requestparam.getContentId());
        return BeanUtil.toBean(contentDO, ContentQueryRespDTO.class);
    }
}
